﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace HgCo.WindowsLive.SkyDrive.TotalCommander.Plugins.Support
{
    /// <summary>
    /// Provides methods for cryptography. 
    /// </summary>
    public class SkyDriveWfxCryptoEngine
    {
        #region Fields

        /// <summary>
        /// The secret key used for TripleDES.
        /// </summary>
        private readonly static byte[] TripleDesKey = Encoding.ASCII.GetBytes("9BMXMfr2EzlkmVbm6XdBPuym");

        /// <summary>
        /// The initialization vector used for TripleDES.
        /// </summary>
        private readonly static byte[] TripleDesIv = Encoding.ASCII.GetBytes("TriplDES");

        #endregion

        #region Methods

        /// <summary>
        /// Encrypts the specified value.
        /// </summary>
        /// <param name="value">The value to encrypt.</param>
        /// <returns>The encrypted value.</returns>
        public static string Encrypt(string value)
        {
            string valueEncrypted = String.Empty;

            if (!String.IsNullOrEmpty(value))
                using (var srvCrypto = new TripleDESCryptoServiceProvider())
                using (var transCrypto = srvCrypto.CreateEncryptor(TripleDesKey, TripleDesIv))
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(value);
                    byte[] bufferEncrypted = transCrypto.TransformFinalBlock(buffer, 0, buffer.Length);
                    valueEncrypted = Convert.ToBase64String(bufferEncrypted);
                }

            return valueEncrypted;
        }

        /// <summary>
        /// Decrypts the spcified value.
        /// </summary>
        /// <param name="value">The value to decrypt.</param>
        /// <returns>The decrypted value.</returns>
        public static string Decrypt(string value)
        {
            string valueDecrypted = String.Empty;

            if (!String.IsNullOrEmpty(value))
                using (var srvCrypto = new TripleDESCryptoServiceProvider())
                using (var transCrypto = srvCrypto.CreateDecryptor(TripleDesKey, TripleDesIv))
                {

                    byte[] buffer = Convert.FromBase64String(value);
                    byte[] bufferDecrypted = transCrypto.TransformFinalBlock(buffer, 0, buffer.Length);
                    valueDecrypted = Encoding.UTF8.GetString(bufferDecrypted);
                }

            return valueDecrypted;
        }

        #endregion
    }
}
